/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.merak.core;

import java.io.File;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.naming.resources.ProxyDirContext;

public final class Initializer {

	//~ Constants ////////////////////////////////////////////////////////////////
	//****************************************************************************
	private static String LOG_OUTPUT_FORMAT = "[%d{dd-MMM HH:MM}] [%-5p] {%c} %m%n";

	//~ Attributes ///////////////////////////////////////////////////////////////
	//****************************************************************************
	private static String  docBase  = null;
	private static Boolean isWebApp = false;

	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	public static void setDocBase(String docBase) {
		Initializer.docBase = docBase;
	}
	//****************************************************************************
	public static void setIsWebApp(Boolean isWebApp) {
		Initializer.isWebApp = isWebApp;
	}
	//****************************************************************************
	protected static String getDocBase() {

		if ( Initializer.docBase == null ) Initializer.detectParams();
		return Initializer.docBase;

	}
	//***************************************************************************
	public static Boolean getIsWebApp() {

		if ( Initializer.docBase == null ) Initializer.detectParams();
		return Initializer.isWebApp;

	}
	//****************************************************************************
	private static void detectParams() {

		/* Remind: To get some jboss data,
		 * use ServerConfigLocator.locate().getServerDataDir() */

		// 2) DETECT TOMCAT: Check if Tomcat Application
		try {
			InitialContext  ctx = new InitialContext();
			ProxyDirContext dir = (ProxyDirContext) ctx.lookup("java:comp/Resources");
			Initializer.isWebApp = true;
			Initializer.docBase  = dir.getDocBase();
			return;
		}
		catch(ClassCastException ex) {
			// This is a Tomcat Application, but there are conflicting JAR files
			throw new RuntimeException(
				"Duplicated JAR file: Application's Naming API is conflicting with Container's API",ex
			);
		}
		catch(NamingException ex) {
			/* This exception just means it isn't a Tomcat Application,
			 * so keep this block here and empty */
		}

		// 3) DETECT DESKTOP: Consider as desktop application if there is no DocBase
		if (Initializer.docBase == null) {
			Initializer.isWebApp = false;
			Initializer.docBase  = new File("").getAbsolutePath();
		}

	}
	//****************************************************************************
	protected static void initLog4j(File log4jXML) {

		// Skip configuration if log4j.xml doesn't exist
		if (!log4jXML.exists()) return;

		// Initialize from our Application's log4j.xml
		DOMConfigurator.configureAndWatch(log4jXML.getAbsolutePath());

		/* The simplest way to detect if log4j was initialized properly or not
		 * is to ask the root logger if it has any appenders attached to it: */
		Logger root = Logger.getRootLogger();
		if (!root.getAllAppenders().hasMoreElements()) {
			// No appenders means log4j is not initialized!
			root.setLevel(Level.INFO);
			root.addAppender( new ConsoleAppender(
					new PatternLayout(Initializer.LOG_OUTPUT_FORMAT))
			);
		}

		// Log
		Logger.getLogger("Core").info(
				"Log4j initialized from " + log4jXML
		);

	}
	//****************************************************************************
	@SuppressWarnings("unused")
	private static boolean isJBossApplication() {

		try {
			// Check JBoss Data directory
			//ServerConfigLocator.locate().getServerDataDir();
			return true;
		}
		catch(NoClassDefFoundError error) {
			return false;
		}

	}
	//****************************************************************************

}
